package saucaca.fragment;

import java.util.ArrayList;

import org.json.JSONException;

import saucaca.Adapter.ExpandableSongAdapter2;
import saucaca.CustomView.ProgressBarCircularIndeterminate;
import saucaca.JSON.JsonReader;
import saucaca.JSON.WServiceLib;
import saucaca.Object.SongObject;
import saucaca.Util.TagName;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lemon.kenhnhacvn.BaseEngine;
import com.lemon.kenhnhacvn.MainActivity;
import com.lemon.kenhnhacvn.R;

public class OnlineSongList2 extends Fragment implements OnScrollListener {
	public static final String TAG = OnlineSongList2.class.getSimpleName();
	ArrayList<SongObject> songs;
	String sType = "1";
	String cateCode = "";
	String singerCode = "";
	String authorCode = "";
	String areaCode = "";
	String typeHot = "1";
	String page = "0";
	String pageSize = "";
	int xpage = 0;
	boolean loadingMore;
	MainActivity mActivity;
	private View mView_EmptyLoading = null;
	private ProgressBar progressBar;
	ImageView imgEmpty, imgError;
	TextView txtStatus;
	boolean isFromMenu;
	TextView txtTitle;

	private ExpandableListView expandListview;
	ProgressBarCircularIndeterminate progressBarFooter;
	ExpandableSongAdapter2 adapter;
	int m_PreviousTotalCount = 0;

	public static OnlineSongList2 newInstance(String cateCode, String singerCode, String authorCode, String areaCode, String page, String pageSize, String typeHot) {
		OnlineSongList2 f = new OnlineSongList2();
		Bundle args = new Bundle();
		args.putString(TagName.cateCode, cateCode);
		args.putString(TagName.singerCode, singerCode);
		args.putString(TagName.authorCode, authorCode);
		args.putString(TagName.areaCode, areaCode);
		args.putString(TagName.page, page);
		args.putString(TagName.pageSize, pageSize);
		args.putString(TagName.typeHot, typeHot);
		f.setArguments(args);
		return f;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mActivity = (MainActivity) getActivity();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View android = inflater.inflate(R.layout.listview_expand2, container, false);
		findviewByID(android);
		if (getArguments() != null) {
			Bundle b = getArguments();
			this.cateCode = b.getString(TagName.cateCode);
			this.singerCode = b.getString(TagName.singerCode);
			this.authorCode = b.getString(TagName.authorCode);
			this.areaCode = b.getString(TagName.areaCode);
			this.page = b.getString(TagName.page);
			this.pageSize = b.getString(TagName.pageSize);
			this.typeHot = b.getString(TagName.typeHot);
			new GetFromServices().execute("");
		}
		return android;
	}

	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
	private void findviewByID(View view) {
		expandListview = (ExpandableListView) view.findViewById(R.id.layoutlistview_ExpandListview);
		expandListview.setOnScrollListener(this);
		progressBarFooter = (ProgressBarCircularIndeterminate) view.findViewById(R.id.progressBarloadmore);
		mView_EmptyLoading = view.findViewById(R.id.empty_loading);
		// mView_EmptyLoading.setVisibility(View.GONE);
		expandListview.setEmptyView(mView_EmptyLoading);
		progressBar = (ProgressBar) mView_EmptyLoading.findViewById(R.id.empty_loading_progress);
		imgEmpty = (ImageView) mView_EmptyLoading.findViewById(R.id.empty_loading_NoItem);
		imgError = (ImageView) mView_EmptyLoading.findViewById(R.id.empty_loading_Error);
		txtStatus = (TextView) mView_EmptyLoading.findViewById(R.id.empty_loading_text);
		songs = new ArrayList<SongObject>();
		adapter = new ExpandableSongAdapter2(mActivity, expandListview, songs);
		expandListview.setAdapter(adapter);
	}

	class GetFromServices extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... param) {
			if (m_PreviousTotalCount > 0)
				getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						progressBarFooter.setVisibility(View.VISIBLE);
					}
				});
			page = Integer.toString(xpage);
			loadingMore = true;
			String str = WServiceLib.listSongVideoAlbum(sType, cateCode, singerCode, authorCode, areaCode, page, pageSize, typeHot);
			// BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result != null)
				try {
					if (getActivity()!=null)
					getActivity().runOnUiThread(new Runnable() {
						@Override
						public void run() {
							progressBarFooter.setVisibility(View.GONE);
						}
					});
					ArrayList<SongObject> listsong = JsonReader.readlistSongFromString(result, TagName.KEY_SONG);
					for (int i = 0; i < listsong.size(); i++) {
						boolean isAdded = false;
						for (int j = 0; j < songs.size(); j++) {
							if (songs.get(j).getSONG_ID().equals(listsong.get(i).getSONG_ID())) {
								isAdded = true;
							}
						}
						if (!isAdded) {
							songs.add(listsong.get(i));
							adapter.update(songs);
						}
					}
					if (songs.size() == 0) {
						progressBar.setVisibility(View.GONE);
						imgEmpty.setVisibility(View.VISIBLE);
						txtStatus.setText(mActivity.getResources().getString(R.string.no_item_song));
					}
					loadingMore = false;
				} catch (JSONException e) {
					e.printStackTrace();
				}
		}

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if (totalItemCount == 0 || adapter == null)
			return;
		if (m_PreviousTotalCount == totalItemCount) {
			return;
		}
		boolean loadMore = firstVisibleItem + visibleItemCount >= totalItemCount - 3;
		if (loadMore && firstVisibleItem > 0 && totalItemCount - m_PreviousTotalCount >= 10) {
			m_PreviousTotalCount = totalItemCount;
			xpage += 1;
			new GetFromServices().execute("");
		}

	}
}
